﻿using AppWebApi.Converts;
using AppWebApi.Mvc;
using AppWebApi.Mvc.Filters;
using Microsoft.OpenApi.Models;
using Modules.System.Settings;
using Modules.System.Settings.Entitys;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Jiguang;
using System.Reflection;

namespace AppWebApi
{
    public static class Builder
    {
        public static void AppWebApi(this WebApplicationBuilder builder) {
            builder.Services.AddControllersWithViews(options =>
            {

                options.Filters.Add<GlobalExceptionFilter>();
            });

            #region Swagger

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //builder.Services.AddSwaggerGen();
            builder.Services.AddSwaggerGen(options =>
            {
                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}（注意两者之间是一个空格）",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey
                });
                options.OperationFilter<SecurityRequirementsOperationFilter>();
                options.SwaggerDoc("v1", new OpenApiInfo { Title = "AppWebApi", Version = "v1", Description = "建筑工人管理系统-AppWebApi" });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath, true);
            });

            #endregion

            builder.Services.ConfigureStateProvider<CurrentUserUserStateProvider>();
            //注入基础组件
            builder.Services.AddPmSoftFrameWork(builder.Configuration, builder.Environment);

            //AutoMapper
            builder.Services.AddAutoMapper(typeof(AutoMapperProfiles));

            //程序集注入
            builder.Services.AutoRegisterServicesFromAssembly("AppWebApi");
            builder.Services.AutoRegisterServicesFromAssembly("Modules");

            builder.Services.AddScoped<IJiguangService, JiguangService>();
            //泛型注入
            builder.Services.AddScoped<SettingManager<CheckinWageStatusSettings>>();
            builder.Services.AddScoped<SettingRepository<CheckinWageStatusSettings>>();

            builder.Services.AddScoped<SettingManager<RetrievePasswordSetting>>();
            builder.Services.AddScoped<SettingRepository<RetrievePasswordSetting>>();

            builder.Services.AddHostedService<ApplicationHostedService>();
        }
    }
}
